<?php

require_once dirname(__FILE__) . '/../lib/usuariosGeneratorConfiguration.class.php';
require_once dirname(__FILE__) . '/../lib/usuariosGeneratorHelper.class.php';

/**
 * usuarios actions.
 *
 * @package    SistemaWebUnlSenescyt
 * @subpackage usuarios
 * @author     JFernando
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class UsuariosActions extends sfActions {

    public function preExecute() {
        $this->configuration = new usuariosGeneratorConfiguration();

        if (!$this->getUser()->hasCredential($this->configuration->getCredentials($this->getActionName()))) {
            $this->forward(sfConfig::get('sf_secure_module'), sfConfig::get('sf_secure_action'));
        }

        $this->dispatcher->notify(new sfEvent($this, 'admin.pre_execute', array('configuration' => $this->configuration)));

        $this->helper = new usuariosGeneratorHelper();

        parent::preExecute();
    }

    public function executeIndex(sfWebRequest $request) {
        // sorting
        if ($request->getParameter('sort') && $this->isValidSortColumn($request->getParameter('sort'))) {
            $this->setSort(array($request->getParameter('sort'), $request->getParameter('sort_type')));
        }

        // pager
        if ($request->getParameter('page')) {
            $this->setPage($request->getParameter('page'));
        }

        $this->pager = $this->getPager();
        $this->sort = $this->getSort();
    }

    public function executeActivar(sfWebRequest $request) {
        // sorting
        $id = $request->getParameter('id');
        $usermo = Doctrine::getTable('sfguarduser')->find($id);
        if (!($usermo instanceof sfGuardUser)) {
            $this->redirect404();
        }
        $usermo['is_active'] = !$usermo['is_active'];
        $usermo->save();

        $this->redirect('usuarios/index');
    }

    public function executeCambiarpassword(sfWebRequest $request) {




        $id = $request->getParameter('id');
        $usermo = Doctrine::getTable('sfguarduser')->find($id);
        $pass = $this->gen_chars_no_dup();
        $usermo->setPassword($pass);
        $usermo->save();

        $transport = Swift_SmtpTransport::newInstance('smtp.googlemail.com', 465, 'ssl')
                ->setUsername('siwebsu@gmail.com')
                ->setPassword('s7i4w9e3b2s7u8')
        ;
        $mailer = Swift_Mailer::newInstance($transport);

        // Create a message                
        $m1 = "BIENVENIDO AL =>SIWEBSU<=\n
                    SISTEMA DE GESTION\n
                    DE PRESUPUESTOS DE PROYECTOS DE INVESTIGACION DESARROLLO E INNOVACION\n
                    Su contraseña ha sido modificada exitosamente";

        $email = $usermo->getEmailAddress();
        $tpas = "\nPassword =>";
        $m2 = "\nPor seguridad le sugerimos cambiar su contraseña";
        $t = $m1 . $tpas . $pass . $m2;

        $message = Swift_Message::newInstance('Notificacion')
                ->setFrom(array('siwebsu@gmail.com' => 'Administrador'))
                ->setTo(array($email => 'user'))
                ->setBody($t)

        ;

        // Send the message
        $result = $mailer->send($message);


        $this->redirect('usuarios/index');
    }

    public function executeFilter(sfWebRequest $request) {
        $this->setPage(1);

        if ($request->hasParameter('_reset')) {
            $this->setFilters($this->configuration->getFilterDefaults());

            $this->redirect('@sfguarduser');
        }

        $this->filters = $this->configuration->getFilterForm($this->getFilters());

        $this->filters->bind($request->getParameter($this->filters->getName()));
        if ($this->filters->isValid()) {
            $this->setFilters($this->filters->getValues());

            $this->redirect('@sfguarduser');
        }

        $this->pager = $this->getPager();
        $this->sort = $this->getSort();

        $this->setTemplate('index');
    }

    public function executeNew(sfWebRequest $request) {
        $this->form = $this->configuration->getForm();
        $this->sfguarduser = $this->form->getObject();
    }

    public function executeCreate(sfWebRequest $request) {
        $this->form = $this->configuration->getForm();
        $this->sfguarduser = $this->form->getObject();

        $this->processForm($request, $this->form);

        $this->setTemplate('new');
    }

    public function executeEdit(sfWebRequest $request) {
        $this->sfguarduser = $this->getRoute()->getObject();
        $this->form = $this->configuration->getForm($this->sfguarduser);
    }

    public function executeEditagregar(sfWebRequest $request) {
        $this->sfguarduser = $this->getRoute()->getObject();
        $this->form = $this->configuration->getForm($this->sfguarduser);
        $aux = 1;
        $this->getUser()->setAttribute('usercrear', $aux);
    }

    public function executeUpdate(sfWebRequest $request) {
        $this->sfguarduser = $this->getRoute()->getObject();
        $this->form = $this->configuration->getForm($this->sfguarduser);
        $nu = $this->getUser()->getAttribute('usercrear');
        if ($nu == 1) {
            $a = 0;
            $this->getUser()->setAttribute('usercrear', $a);
            $this->processForm($request, $this->form);
        } else {
            $this->processFormEdit($request, $this->form);
        }




        $this->setTemplate('edit');
    }

    public function executeDelete(sfWebRequest $request) {
        $request->checkCSRFProtection();

        $this->dispatcher->notify(new sfEvent($this, 'admin.delete_object', array('object' => $this->getRoute()->getObject())));

        if ($this->getRoute()->getObject()->delete()) {
            $this->getUser()->setFlash('notice', ' El item Se ha borrado exitosamente.');
        }

        $this->redirect('@sfguarduser');
    }

    public function executeBatch(sfWebRequest $request) {
        $request->checkCSRFProtection();

        if (!$ids = $request->getParameter('ids')) {
            $this->getUser()->setFlash('error', 'You must at least select one item.');

            $this->redirect('@sfguarduser');
        }

        if (!$action = $request->getParameter('batch_action')) {
            $this->getUser()->setFlash('error', 'You must select an action to execute on the selected items.');

            $this->redirect('@sfguarduser');
        }

        if (!method_exists($this, $method = 'execute' . ucfirst($action))) {
            throw new InvalidArgumentException(sprintf('You must create a "%s" method for action "%s"', $method, $action));
        }

        if (!$this->getUser()->hasCredential($this->configuration->getCredentials($action))) {
            $this->forward(sfConfig::get('sf_secure_module'), sfConfig::get('sf_secure_action'));
        }

        $validator = new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => 'sfguarduser'));
        try {
            // validate ids
            $ids = $validator->clean($ids);

            // execute batch
            $this->$method($request);
        } catch (sfValidatorError $e) {
            $this->getUser()->setFlash('error', 'A problem occurs when deleting the selected items as some items do not exist anymore.');
        }

        $this->redirect('@sfguarduser');
    }

    public function executeError(sfWebRequest $request) {
        //acciones
    }

    protected function executeBatchDelete(sfWebRequest $request) {
        $ids = $request->getParameter('ids');

        $records = Doctrine_Query::create()
                ->from('sfguarduser')
                ->whereIn('id', $ids)
                ->execute();

        foreach ($records as $record) {
            $this->dispatcher->notify(new sfEvent($this, 'admin.delete_object', array('object' => $record)));

            $record->delete();
        }

        $this->getUser()->setFlash('notice', 'The selected items have been deleted successfully.');
        $this->redirect('@sfguarduser');
    }

    function gen_chars_no_dup($long=8) {
        $chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        mt_srand((double) microtime() * 1000000);
        $i = 0;
        $pass="user";
        while ($i != $long) {
            $rand = mt_rand() % strlen($chars);
            $tmp = $chars[$rand];
            $pass = $pass . $tmp;
            $chars = str_replace($tmp, "", $chars);
            $i++;
        }
        return strrev($pass);
    }

    protected function processFormEdit(sfWebRequest $request, sfForm $form) {

        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {


            try {

                try {
                    $sfguarduser = $form->save();

                    $transport = Swift_SmtpTransport::newInstance('smtp.googlemail.com', 465, 'ssl')
                            ->setUsername('siwebsu@gmail.com')
                            ->setPassword('s7i4w9e3b2s7u8')
                    ;
                    $mailer = Swift_Mailer::newInstance($transport);

                    // Create a message                
                    $m1 = "BIENVENIDO AL =>SIWEBSU<=\n
                    SISTEMA DE GESTION\n
                    DE PRESUPUESTOS DE PROYECTOS DE INVESTIGACION DESARROLLO E INNOVACION\n
                    Sus datos personales han sido cambiados exitosamente";


                    $tdni = "\nDNI =>";
                    $dni = $sfguarduser->getDni();
                    $tn = "\nNombres =>";
                    $nom = $sfguarduser->getName();
                    $ta = "\nApellidos =>";
                    $ape = $sfguarduser->getLastName();
                    $tce = "\nCorreo Electronico =>";
                    $email = $sfguarduser->getEmailAddress();
                    $tg = "\nGenero =>";
                    if ($sfguarduser->getSexo() == 0) {
                        $gen = "masculino";
                    } else {
                        $gen = "femenino";
                    }
                    $tdd = "\nDireccion Domiciliaria =>";
                    $dd = $sfguarduser->getDireccion();
                    $tt = "\nTelefono =>";
                    $tel = $sfguarduser->getTelefono();
                    $tc = "\nCelular =>";
                    $cel = $sfguarduser->getTelefonoMovil();
                    $tun = "\nUsername =>";
                    $u = $sfguarduser->getUsername();



                    $m2 = "\n\nPor favor cuide su informacion personal";
                    $t = $m1 . $tdni . $dni . $tn . $nom . $ta . $ape . $tce . $email . $tg . $gen . $tdd . $dd . $tt . $tel . $tc . $cel . $tun . $u;

                    $message = Swift_Message::newInstance('Notificacion')
                            ->setFrom(array('siwebsu@gmail.com' => 'Administrador'))
                            ->setTo(array($email => 'user'))
                            ->setBody($t)

                    ;

                    // Send the message
                    $result = $mailer->send($message);
                    $this->getUser()->setFlash('notice', 'Cambio exitoso de datos.');
                } catch (Exception $e) {
                    $this->getUser()->setFlash('error', 'Error en ingreso de datos.', false);
                }
            } catch (Doctrine_Validator_Exception $e) {

                $errorStack = $form->getObject()->getErrorStack();

                $message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ? 's' : null) . " with validation errors: ";
                foreach ($errorStack as $field => $errors) {
                    $message .= "$field (" . implode(", ", $errors) . "), ";
                }
                $message = trim($message, ', ');

                $this->getUser()->setFlash('error', $message);
                return sfView::SUCCESS;
            }

            //$this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $sfguarduser)));

            if ($request->hasParameter('_save_and_add')) {
                $this->getUser()->setFlash('notice', $notice . ' You can add another one below.');

                $this->redirect('@sfguarduser_new');
            } else {
                //$this->getUser()->setFlash('notice', $notice);
//
                //$this->redirect(array('sf_route' => 'sfguarduser_edit', 'sf_subject' => $sfguarduser));
            }
        } else {
            $this->getUser()->setFlash('error', 'The item has not been saved due to some errors.', false);
        }
    }

    protected function processForm(sfWebRequest $request, sfForm $form) {

        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {


            try {
                $p = $this->gen_chars_no_dup();
                $form->getObject()->setPassword($p);
                try {
                    $sfguarduser = $form->save();
                    $transport = Swift_SmtpTransport::newInstance('smtp.googlemail.com', 465, 'ssl')
                            ->setUsername('siwebsu@gmail.com')
                            ->setPassword('s7i4w9e3b2s7u8')
                    ;
                    $mailer = Swift_Mailer::newInstance($transport);

                    // Create a message                
                    $m1 = "BIENVENIDO AL =>SIWEBSU<=\n
                    SISTEMA DE GESTION\n
                    DE PRESUPUESTOS DE PROYECTOS DE INVESTIGACION DESARROLLO E INNOVACION\n
                    Su cuenta ha sido creada satisfactoriamente con los siguientes datos";
                    $tun = "\nUsername =>";
                    $u = $sfguarduser->getUsername();
                    $email = $sfguarduser->getEmailAddress();
                    $tpas = "\nPassword =>";
                    $m2 = "\nPor seguridad le sugerimos cambiar su contraseña";
                    $t = $m1 . $tun . $u . $tpas . $p . $m2;

                    $message = Swift_Message::newInstance('Notificacion')
                            ->setFrom(array('siwebsu@gmail.com' => 'Administrador'))
                            ->setTo(array($email => 'user'))
                            ->setBody($t)

                    ;

                    // Send the message
                    $result = $mailer->send($message);
                    $this->getUser()->setFlash('notice', 'Datos agregados exitosamente');
                } catch (Exception $e) {
                    //aqui va
//                    $this->getUser()->setFlash('error', 'Nombre de Usuario repetido.', false);
                }




                //printf("Sent %d messages\n", $result);
            } catch (Doctrine_Validator_Exception $e) {

                $errorStack = $form->getObject()->getErrorStack();

                $message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ? 's' : null) . " with validation errors: ";
                foreach ($errorStack as $field => $errors) {
                    $message .= "$field (" . implode(", ", $errors) . "), ";
                }
                $message = trim($message, ', ');

                $this->getUser()->setFlash('error', $message);
                return sfView::SUCCESS;
            }

            //$this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $sfguarduser)));

            if ($request->hasParameter('_save_and_add')) {
                $this->getUser()->setFlash('notice', $notice . ' You can add another one below.');

                $this->redirect('@sfguarduser_new');
            } else {
                //$this->getUser()->setFlash('notice', $notice);
                //$this->redirect(array('sf_route' => 'sfguarduser_edit', 'sf_subject' => $sfguarduser));
            }
        } else {
            $this->getUser()->setFlash('error', 'The item has not been saved due to some errors.', false);
        }
    }

    protected function getFilters() {
        return $this->getUser()->getAttribute('usuarios.filters', $this->configuration->getFilterDefaults(), 'admin_module');
    }

    protected function setFilters(array $filters) {
        return $this->getUser()->setAttribute('usuarios.filters', $filters, 'admin_module');
    }

    protected function getPager() {
        $pager = $this->configuration->getPager('sfguarduser');
        $pager->setQuery($this->buildQuery());
        $pager->setPage($this->getPage());
        $pager->init();

        return $pager;
    }

    protected function setPage($page) {
        $this->getUser()->setAttribute('usuarios.page', $page, 'admin_module');
    }

    protected function getPage() {
        return $this->getUser()->getAttribute('usuarios.page', 1, 'admin_module');
    }

    protected function buildQuery() {
        $tableMethod = $this->configuration->getTableMethod();
        if (null === $this->filters) {
            $this->filters = $this->configuration->getFilterForm($this->getFilters());
        }

        $this->filters->setTableMethod($tableMethod);

        $query = $this->filters->buildQuery($this->getFilters());

        $this->addSortQuery($query);

        $event = $this->dispatcher->filter(new sfEvent($this, 'admin.build_query'), $query);
        $query = $event->getReturnValue();

        return $query;
    }

    protected function addSortQuery($query) {
        if (array(null, null) == ($sort = $this->getSort())) {
            return;
        }

        if (!in_array(strtolower($sort[1]), array('asc', 'desc'))) {
            $sort[1] = 'asc';
        }

        $query->addOrderBy($sort[0] . ' ' . $sort[1]);
    }

    protected function getSort() {
        if (null !== $sort = $this->getUser()->getAttribute('usuarios.sort', null, 'admin_module')) {
            return $sort;
        }

        $this->setSort($this->configuration->getDefaultSort());

        return $this->getUser()->getAttribute('usuarios.sort', null, 'admin_module');
    }

    protected function setSort(array $sort) {
        if (null !== $sort[0] && null === $sort[1]) {
            $sort[1] = 'asc';
        }

        $this->getUser()->setAttribute('usuarios.sort', $sort, 'admin_module');
    }

    protected function isValidSortColumn($column) {
        return Doctrine_Core::getTable('sfguarduser')->hasColumn($column);
    }

}

